/*
 * Copyright (c) 2009. Silenus Consultoria, S.L.
 */
package es.silenus.detecta.dao.impl;

import es.silenus.detecta.dao.Page;
import es.silenus.detecta.dao.QualificationDAO;

import es.silenus.detecta.model.KnowledgeUnit;
import es.silenus.detecta.model.Qualification;

import org.hibernate.FetchMode;
import org.hibernate.Hibernate;
import org.hibernate.Session;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import static java.util.Arrays.asList;
import java.util.List;
import java.util.Map;


/**
 * DOCUMENT ME!
 *
 * @author <a href="mailto:dgarcia@silenus-consultoria.es">Daniel Garc&iacute;a</a>
 *
 * @since 02-abr-2009 12:38:12
 */
public class QualificationDAOImpl extends ReadWriteDAOImpl<Qualification, Integer> implements QualificationDAO {
	/**
	 * The check remove qualifications SQL.
	 */
	private String checkRemoveQualificationsSQL;

	/**
	 * Sets the check remove path SQL.
	 *
	 * @param checkRemoveQualificationsSQL the check remove path SQL.
	 */
	public void setCheckRemoveQualificationsSQL(String checkRemoveQualificationsSQL) {
		this.checkRemoveQualificationsSQL = checkRemoveQualificationsSQL;
	}

	/**
	 * Retrieves the qualifications a given organization owns.
	 *
	 * @param organizationId the organization id.
	 *
	 * @return the list of qualifications.
	 */
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public List<Qualification> findByOrganization(int organizationId) {
		Session session = null;

		try {
			session = getSession();

			return (List<Qualification>)session.getNamedQuery(Qualification.class.getName() + ".findByOrganization")
																				 .setInteger("organizationId", organizationId)
																				 .setResultTransformer(DetachedCriteria.DISTINCT_ROOT_ENTITY).list();
		} finally {
			releaseSession(session);
		}
	}

	/**
	 * Loads every single instance of a persistent class.
	 *
	 * @return list of instances.
	 */
	@Override
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public List<Qualification> findAll() {
		Session session = null;

		try {
			session = getSession();

			return session.getNamedQuery(Qualification.class.getName() + ".findAll")
										.setResultTransformer(DetachedCriteria.DISTINCT_ROOT_ENTITY).list();
		} finally {
			releaseSession(session);
		}
	}

	/**
	 * Finds a qualification given its code and organization id.
	 *
	 * @param code the code.
	 * @param organizationId the organization id.
	 *
	 * @return the area.
	 */
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public Qualification findByCode(final String code, int organizationId) {
		Session session = null;

		try {
			session = getSession();

			return (Qualification)session.getNamedQuery(Qualification.class.getName() + ".findByCode").setString(
				"code", code).setInteger("organizationId", organizationId).uniqueResult();
		} finally {
			releaseSession(session);
		}
	}

	/**
	 * Override this method to provide a find by example page criteria.
	 *
	 * @param criteria the criteria.
	 * @param object the sample object.
	 *
	 * @return the criteria.
	 */
	protected DetachedCriteria preparePageCriteria(final DetachedCriteria criteria, final Map<String, Object> object) {
		criteria.setFetchMode("organization", FetchMode.JOIN);

		Object temp = object.get("id");

		if(temp != null) {
			criteria.add(Restrictions.eq("id", temp));
		}

		temp = object.get("code");

		if(temp != null) {
			criteria.add(Restrictions.ilike("code", (String)temp, MatchMode.ANYWHERE));
		}

		temp = object.get("description");

		if(temp != null) {
			criteria.add(Restrictions.ilike("description", (String)temp, MatchMode.ANYWHERE));
		}

		temp = object.get("organization.id");

		if(temp != null) {
			criteria.add(Restrictions.eq("organization.id", temp));
		}


		return criteria;
	}

	/**
	 * Override this method to provide a find by example list criteria.
	 *
	 * @param criteria the criteria.
	 * @param object the sample object.
	 *
	 * @return the criteria.
	 */
	protected DetachedCriteria prepareListCriteria(final DetachedCriteria criteria, final Map<String, Object> object) {
		return preparePageCriteria(criteria, object);
	}

	/**
	 * Finds units associated with the given criteria.
	 *
	 * @param sample the sample criteria.
	 * @param start the start index.
	 * @param limit the limit index.
	 * @param sortFields the sort fields.
	 * @param sortDirections the sort directions.
	 *
	 * @return the page.
	 */
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public Page<KnowledgeUnit> findAssociatedUnits(
		final Map<String, Object> sample, int start, int limit, final String[] sortFields, final String[] sortDirections) {
		DetachedCriteria criteria = DetachedCriteria.forEntityName("KnowledgeUnit");

		// Prepare the page criteria
		criteria.add(
			Restrictions.sqlRestriction(
				"EXISTS (SELECT 1 FROM qualification_units a WHERE a.id_unit={alias}.id_unit AND a.id_qualification=?)",
				sample.get("id"), Hibernate.INTEGER));


		// Build page and paginate
		PageImpl<KnowledgeUnit> page = new PageImpl<KnowledgeUnit>(getSessionFactory());

		page.setStart(start);
		page.setLimit(limit);
		page.setCriteria(criteria);

		if((sortFields != null) && (sortDirections != null) && (sortFields.length == sortDirections.length)) {
			for(int i = 0; i < sortFields.length; ++i) {
				page.addSort(sortFields[i], sortDirections[i]);
			}
		}

		page.paginate();

		return page;
	}

	/**
	 * Finds units non associated with the given criteria.
	 *
	 * @param sample the sample criteria.
	 * @param start the start index.
	 * @param limit the limit index.
	 * @param sortFields the sort fields.
	 * @param sortDirections the sort directions.
	 *
	 * @return the page.
	 */
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public Page<KnowledgeUnit> findNonAssociatedUnits(
		final Map<String, Object> sample, int start, int limit, final String[] sortFields, final String[] sortDirections) {
		DetachedCriteria criteria = DetachedCriteria.forEntityName("KnowledgeUnit");

		// Prepare the page criteria
		criteria.add(
			Restrictions.sqlRestriction(
				"NOT EXISTS (SELECT 1 FROM qualification_units a WHERE a.id_unit={alias}.id_unit AND a.id_qualification=?)",
				sample.get("id"), Hibernate.INTEGER));


		// Build page and paginate
		PageImpl<KnowledgeUnit> page = new PageImpl<KnowledgeUnit>(getSessionFactory());

		page.setStart(start);
		page.setLimit(limit);
		page.setCriteria(criteria);

		if((sortFields != null) && (sortDirections != null) && (sortFields.length == sortDirections.length)) {
			for(int i = 0; i < sortFields.length; ++i) {
				page.addSort(sortFields[i], sortDirections[i]);
			}
		}

		page.paginate();

		return page;
	}

	/**
	 * Retrieves the removal information of entities with the given keys.
	 *
	 * @param keys the keys.
	 *
	 * @return the information requested.
	 */
	@SuppressWarnings({"unchecked"})
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public List<Map<String, Object>> getRemovalInformation(final Integer[] keys) {
		MapSqlParameterSource args = new MapSqlParameterSource();

		args.addValue("ids", asList(keys));

		return jdbcTemplate.queryForList(checkRemoveQualificationsSQL, args);
	}

	/**
	 * Removes qualifications by keys.
	 *
	 * @param keys the keys.
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public void remove(final Integer[] keys) {
		List<Qualification> elements = findByIds(keys);

		for(Qualification element : elements) {
			super.remove(element);
		}
	}
}
